<template>
  <Teleport to="body">
    <div :class="{ 'is--visible': visible }" :style="style" class="vxe-table--context-menu-wrapper">
      <MenuOptions
        :isChild="false"
        :childName="''"
        v-click-outside="{
          handler: () => (visible = false),
          capture: true,
          events: ['click', 'contextmenu'],
        }"
        :list="options[0]"
        @OptionClick="handleClick"
      >
        <template v-for="(item, key) in slots" :key="key" #[key]="data">
          <slot :name="key" v-bind="data" />
        </template>
      </MenuOptions>
    </div>
  </Teleport>
</template>
<script lang="ts" setup>
import { VXETable } from 'vxe-table';
import MenuOptions from './menuOptions.vue';
import { menuConfig, getDomNode } from '../utils/utils';
const visible = ref(false);
const slots = useSlots();
const style = ref({
  left: '0px',
  top: '0px',
});
const parameters = ref();
const options = ref(menuConfig!.body!.options!);

// VXETable.interceptor();
function handleClick(item: any) {
  if (!(item.children?.length > 0)) {
    visible.value = false;
  }
  VXETable.menus.get(item.code)?.menuMethod!(
    { ...parameters.value, menu: item },
    parameters.value.$event
  );
}
onMounted(() => {
  VXETable.interceptor.add('event.showMenu', (params: any) => {
    params.$event.preventDefault();
    parameters.value = params;
    visible.value = menuConfig?.visibleMethod!({ ...params, options: options.value }) ?? true;
    const { scrollTop, scrollLeft, visibleHeight, visibleWidth } = getDomNode();
    let top = params.$event.clientY + scrollTop;
    let left = params.$event.clientX + scrollLeft;
    style.value = {
      top: top + 'px',
      left: left + 'px',
    };
    return false;
  });
});
watch(
  () => visible.value,
  (flag: boolean) => {
    let activeDom = document.querySelector('.operator-cell-active');
    if (activeDom) {
      activeDom.classList.remove('operator-cell-active');
    }
    if (flag && !!parameters.value.cell) {
      parameters.value.cell.classList.add('operator-cell-active');
    }
  }
);
onUnmounted(() => {
  VXETable.interceptor.delete('event.showMenu');
});
</script>
<style></style>
